<template>
  <div class="app-container">
    <el-page-header @back="$router.back()" :content="form.subject"></el-page-header>

    <div class="app-container-main">
      <el-form :model="form" ref="form" :rules="rules" :inline="true" label-width="150px">
        <el-row>
          <div>
            <el-col :span="24">
              <div class="title">运费试算</div>
            </el-col>
            <el-col :span="24">
              <el-form-item class="flexbox" prop="absoluteQuoteType">
                <div class="border-box">
                  <div class="title">
                    <el-button size="mini" @click="areaPriceEdit" :disabled="isSave">选择区域</el-button>
                  </div>
                  <div class="tagBox">
                    <div class="tagBox-item">
                      <div class="tagBox-item-list">
                        <el-tag
                          v-for="tag in checkedCities"
                          :key="tag.lable"
                          :disable-transitions="false">
                          {{ tag.value }}[{{ tag.lable }}]
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <div>
                <el-button size="mini" @click="areaBatchSet" :disabled="isSave">批量设置</el-button>
                <div class="box-flex" v-if="areaSetModel">
                  <el-form :inline="true">
                    <el-form-item label="区域">
                      <el-select v-model="areaForm.areaId" multiple placeholder="区域选择" clearable>
                        <el-option
                          v-for="dict in checkedCities"
                          :key="dict.value"
                          :label="dict.lable"
                          :value="dict.lable"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="价格">
                      <el-input v-model="areaForm.price"></el-input>
                    </el-form-item>
                    <el-button size="small" type="primary" @click="areaBatchBtn(true)">确定</el-button>
                    <el-button size="small" @click="areaBatchBtn(false)">取消</el-button>
                  </el-form>
                </div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="tabblebox">
                <el-table
                  :data="newAreaList"
                  border
                  :header-cell-style="{'text-align':'center'}"
                  :cell-style="{'text-align':'center'}"
                  header-cell-class-name="table-header"
                  width="100%"
                  current-row-key="uid"
                  row-class-name="table-row">
                  <template v-if="form.expand">
                    <el-table-column
                      v-for="(leftTitle) in JSON.parse(form.expand.skuProperty || '[]')"
                      :key="leftTitle.value"
                      :label="leftTitle.name"
                    >
                      <template slot-scope="scope">
                        {{ propertyLabel(scope.row.skuPropertyIds, leftTitle.value) }}
                      </template>
                    </el-table-column>
                  </template>
                  <el-table-column
                    v-for="(leftTitle, index) in absoluteQuoteMap"
                    :key="leftTitle.shiptoCountry"
                    :label="leftTitle.shiptoCountry"
                    width="90"
                  >
                    <template slot-scope="scope">
                      <el-form-item :prop="absoluteQuoteMapProp(scope.row, leftTitle)">
                        <el-input-number
                          :disabled="isSave"
                          :controls="false"
                          :min="0"
                          :value="absoluteQuoteMapValue(scope.row, leftTitle)"
                          @input="val => absoluteQuoteMapInput(val, scope.row, index)"
                        />
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </div>
          <el-col :span="24">
            <div class="button">
              <el-button v-if="!isSave" :loading="buttonLoading" :disabled="buttonLoading" type="primary"
                         @click="revise">确认已完成
              </el-button>
              <el-button v-if="isSave" :disabled="trialLoading" @click="reEditBtn">重新编辑</el-button>
              <el-button v-if="isSave" :loading="trialLoading" :disabled="trialLoading" type="primary"
                         @click="reTrialBtn">重新运费试算
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 区域定价弹框 -->
    <el-dialog title="请选择" :visible.sync="open" width="50%" append-to-body>
      <template>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
        </el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="areaPriceSelected" @change="handleCheckedCitiesChange">
          <el-checkbox
            v-for="item in areaList"
            :label="item.lable"
            :key="item.lable"
          >{{ item.value }}[{{ item.lable }}]
          </el-checkbox>
        </el-checkbox-group>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="areaPriceComplete(true)">确 定</el-button>
        <el-button @click="areaPriceComplete(false)">取 消</el-button>
      </div>
    </el-dialog>

    <el-backtop></el-backtop>
  </div>
</template>

<script>
import {getCollectProduct, updateCollectProduct, refreshFreightTask} from "@/api/persongather/collectProduct";
import {getArea} from "@/api/attribute"
import uuid from '@/utils/uuid'

export default {
  data() {
    return {
      form: {
        expand: {
          'skuProperty': '[]',
          'absoluteQuoteType': null
        }
      },
      // sku列表批量设置表单
      skuForm: {
        skuPrice: null,
        skuStock: null,
        skuBuyLink: null
      },
      skuSetModel: false,
      // 区域列表批量设置表单
      areaForm: {
        price: null,
        areaId: null
      },
      areaSetModel: false,
      // 遮罩层
      loading: true,
      // 按钮loading
      buttonLoading: false,
      // 区域定价弹框
      open: false,
      // 表单校验
      rules: {},
      // 全选
      checkAll: false,
      // 全选
      isIndeterminate: false,
      // 选中区域列表
      areaPriceSelected: [],
      // 全部区域列表
      areaList: [],
      // 控制按钮
      isSave: true,
      trialLoading: false
    }
  },
  computed: {
    // sku商品
    propertyLabel() {
      if (this.form.expand) {
        const ls = JSON.parse(this.form.expand.skuProperty || '[]')
        return (ids, val) => {
          try {
            const items = ids
              .split(';').filter(item => !!item && new RegExp(`^${val}:[0-9]+`).test(item))
              .map(it => {
                const [p1, p2] = it.split(':').filter(item => !!item)
                return ls.filter(item => item.value == p1)[0].list.filter(item => item.value == p2)[0]
              })
            return items[0].name
          } catch (e) {
            return '-'
          }
        }
      } else return '-'
    },
    // sku列表数据
    newSkuList() {
      if (this.form.expand) {
        const skuProperty = JSON.parse(this.form.expand.skuProperty || '[]')
        const idsArr = []
        skuProperty.forEach((p1, p1Index) => {
          (p1.list || []).forEach((p2, p2Index) => {
            if (!idsArr[p1Index]) idsArr.push([])
            idsArr[p1Index].push(`${p1.value}:${p2.value}`)
          })
        })
        const skuPropertyIdsArr = skuPropertyPackage(idsArr, 0)
        // console.log('skuPropertyIdsArr', skuPropertyIdsArr)
        const list = skuPropertyIdsArr.map(ids => {
          const rowData = this.getRowData(ids)
          return rowData
        })
        return list
      } else return []
    },
    // 区域定价数据
    absoluteQuoteMap: {
      get() {
        if (this.form.expand) {
          return JSON.parse(this.form.expand.freightMap || '[]')
        } else {
          return []
        }
      },
      set(val) {
        if (this.form.expand) {
          this.$set(this.form.expand, 'freightMap', JSON.stringify(val || []))
        } else {
          this.form.expand = {
            freightMap: JSON.stringify(val || [])
          }
        }
      }
    },
    // 区域定价的国家数据
    checkedCities() {
      const selectCountrys = this.absoluteQuoteMap.map(item => item.shiptoCountry)
      return this.areaList.filter(item => selectCountrys.includes(item.lable))
    },
    // 区域列表数据
    newAreaList() {
      // const absoluteQuoteMap = this.absoluteQuoteMap
      return this.newSkuList.map(sku => ({
        ...sku,
      }))
    },
    // 区域定价，输入框 value
    absoluteQuoteMapValue() {
      return (row, column) => {
        const value = (column.absoluteQuoteMap || {})[row.skuPropertyIds.replace(/\,/g, ',')] || '0'
        // debugger
        return value
      }
    },
    absoluteQuoteMapProp() {
      return (row, column) => {
        const prop = encodeURIComponent(`absoluteQuoteMap_${column.shiptoCountry}_${row.skuPropertyIds}`)
        // console.log(prop)
        return prop
      }
    }
  },
  methods: {
    // 区域批量设置
    areaBatchSet() {
      this.areaForm = {
        price: null,
        areaId: null
      }
      this.areaSetModel = !this.areaSetModel
    },
    // 区域批量设置确定取消
    areaBatchBtn(isShow) {
      if (isShow) {
        const ls = [...this.absoluteQuoteMap]
        if (this.areaForm.areaId.length <= 0) {
          ls.forEach((item) => {
            for (let key in item.absoluteQuoteMap) {
              item.absoluteQuoteMap[key] = this.areaForm.price
            }
          })
          this.absoluteQuoteMap = ls
        } else {
          ls.forEach((item) => {
            this.areaForm.areaId.forEach(child => {
              if (item.shiptoCountry == child) {
                for (let key in item.absoluteQuoteMap) {
                  item.absoluteQuoteMap[key] = this.areaForm.price
                }
              }
            })
          })
          this.absoluteQuoteMap = ls
        }
      } else {
        this.areaForm = {
          price: null,
          areaId: null
        }
        this.areaSetModel = false
      }
    },
    // 区域定价，输入框 @input
    absoluteQuoteMapInput(price, row, index) {
      const ls = [...this.absoluteQuoteMap]
      const key = row.skuPropertyIds.replace(/\,/g, ',')
      ls[index].absoluteQuoteMap[key] = price
      this.absoluteQuoteMap = ls
    },
    // 区域定价修改
    areaPriceEdit() {
      this.open = true
      this.areaPriceSelected = this.checkedCities.map(item => item.lable)
    },
    // 区域定价 确认
    areaPriceComplete(isSave) {
      if (isSave) {
        const ls = [...this.absoluteQuoteMap]
        this.absoluteQuoteMap = this.areaPriceSelected.map(lable => {
          const i = ls.findIndex(item => item.shiptoCountry === lable)
          if (i !== -1) {
            return {...ls[i]}
          } else {
            return ({
              "absoluteQuoteMap": {},
              "shiptoCountry": lable
            })
          }
        })
        this.newSkuList.forEach(row => {
          this.absoluteQuoteMap.forEach((column, index) => {
            this.rules[encodeURIComponent(`absoluteQuoteMap_${column.shiptoCountry}_${row.skuPropertyIds}`)] = [
              {
                trigger: ['blur', 'change'],
                validator: (rules, _, cb) => {
                  const value = this.absoluteQuoteMapValue(row, this.absoluteQuoteMap[index])
                  if (Number(value)) cb()
                  else cb(new Error(`请输入${column.shiptoCountry}价格`))
                }
              }
            ]
          })
        })
      }
      this.open = false
      this.areaPriceSelected = []
    },
    getRowData(ids) {
      const idsArr = ids.split(',').filter(item => !!item)
      const item = this.form.skuList.filter(item => {
        const skuPropertyIds = item.skuPropertyIds.split(';').filter(item => !!item)
        return ArrayIsSame(skuPropertyIds, idsArr)
      })[0]
      if (item) {
        item.uid = item.id
        return item
      } else {
        return {
          uid: uuid(),
          skuImage: null,
          skuPrice: null,
          skuStock: null,
          skuLength: null,
          skuHeight: null,
          skuWidth: null,
          skuWeight: null,
          skuBuyLink: null,
          skuPropertyIds: ids.toString()
        }
      }
    },
    /** 查询采集商品详情 */
    getInfo(id) {
      this.loading = true;
      getCollectProduct(id).then(res => {
        if (res.data.expand) {
          this.form = res.data
        } else {
          this.form = {
            ...res.data, 'expand': {
              'skuProperty': '[]',
              'absoluteQuoteType': null
            }
          }
        }
        this.loading = false;
      });
    },
    // 获取区域定价国家选择列表
    getAreaList() {
      this.loading = true;
      getArea().then(res => {
        this.areaList = res.data
        this.loading = false;
      });
    },
    // 修改
    revise() {
      if (this.checkedCities.length > 0) {
        this.$refs["form"].validate((valid, obj) => {
          if (valid) {
            this.buttonLoading = true;
            updateCollectProduct(this.form).then(res => {
              this.$modal.msgSuccess("编辑成功");
              this.isSave = true;
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            var a = [];
            for (let key in obj) {
              a.push(obj[key][0].message);
            }
            this.$message({
              message: a[0],
              type: "warning",
            });
            return false;
          }
        })
      } else {
        this.$modal.msgWarning("请先选择区域");
      }
    },
    // 重新编辑
    reEditBtn() {
      this.isSave = false;
    },
    // 重新运费试算
    reTrialBtn() {
      this.$modal.confirm('是否重新运费试算？').then(() => {
        this.trialLoading = true;
        const params = {
          collectProductId: this.$route.params.goodsId,
          type: '2'
        }
        return refreshFreightTask(params);
      }).then(() => {
        this.$modal.msgSuccess("等待运算中");
        this.trialLoading = false;
        this.$router.push(`/persongather/pergoodsList`);
      }).catch((e) => {
      }).finally(() => {
        this.trialLoading = false;
      });
    },
    // 区域全选
    handleCheckAllChange(val) {
      if (val) {
        this.areaPriceSelected = this.areaList.map(item => item.lable)
      } else {
        this.areaPriceSelected = []
      }
      this.isIndeterminate = false
    },
    // 选择区域
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.areaList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.areaList.length;
    }
  },
  created() {
    if (this.$route.params.goodsId) {
      this.getInfo(this.$route.params.goodsId)
    } else {
      this.form = {
        'expand': {
          'skuProperty': '[]',
          'absoluteQuoteType': null
        }
      }
    }
    this.getAreaList();
  }
}

// 相同sku比较
function ArrayIsSame(_arr1, _arr2) {
  const arr1 = [..._arr1]
  const arr2 = [..._arr2]
  // 长度比较
  if (arr1.length !== arr2.length) return false
  // 项比较
  while (arr1.length > 0) {
    if (arr2.includes(arr1[0])) {
      const index = arr2.indexOf(arr1[0])
      arr1.splice(0, 1)
      arr2.splice(index, 1)
    } else {
      return false
    }
  }
  return true
}

// 商品规格包装数据
function skuPropertyPackage(skuProperty, index = 0) {
  const ids = [];
  (skuProperty[index] || []).forEach(item => {
    const _ids = [];
    const otherIds = skuPropertyPackage(skuProperty, index + 1)
    if (otherIds.length) {
      _ids.push(...otherIds.map(child => `${item},${child}`))
    } else {
      _ids.push(item)
    }
    ids.push(..._ids)
  })
  return ids
}

</script>

<style lang="scss">
.app-container {
  .app-container-main {
    padding-top: 25px;

    label {
      font-weight: normal;
    }

    .el-col {
      div {
        background: transparent;
      }

      .vue-treeselect__menu {
        background: #ffffff;
      }
    }

    .title {
      margin: 5px 0 25px 0px;
      padding: 5px 15px;
      background-color: #f6f6f6 !important;
      line-height: 40px;
      font-size: 14px;
      font-weight: 800;
      text-align: left;
    }

    .paddingLeft-box {
      padding-left: 150px;
      width: 100%;
      margin-bottom: 22px;
    }

    .flexbox {
      width: 100%;
      display: flex;

      .el-form-item__content {
        flex: 1;
      }
    }

    .showBox {
      .showBox-item {
        width: 100%;
        padding-bottom: 20px;
      }

      .showBox-button {
        display: flex;
        padding: 0 15px 20px;
      }
    }

    .tagBox {
      .tagBox-item {
        .tagBox-item-name {
          display: flex;
          align-items: center;

          .name-text {
            line-height: 26px;
            display: block;
          }

          .noneBorder {
            border: none;
            margin-left: 10px;
          }
        }
      }

      .el-tag {
        margin-right: 10px;
      }

      .button-new-tag {
        margin-right: 0px;
      }

      .input-new-tag {
        width: 90px;
        margin-right: 10px;
        vertical-align: bottom;
      }
    }

    .border-box {
      border: 1px solid #EBEEF5;
      width: 100%;
      padding: 20px;

      .title {
        margin: 0 0 10px;
      }

      .box-input-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .el-input {
          width: 45%;
        }

        span {
          font-size: 14px;
          line-height: 36px;
          color: #999999;
          cursor: pointer;

          &:hover {
            color: #1890ff;
          }
        }
      }
    }

    .box-flex {
      padding: 30px 0;

      .el-form-item {
        margin-bottom: 0;
      }
    }

    .text-input {
      display: block;
      margin-bottom: 22px;

      .span {
        font-size: 12px;
        line-height: 36px;
        color: #999999;
        padding-left: 10px;
      }

      .el-checkbox {
        display: flex;
        align-items: center;

        .el-checkbox__input {
          padding: 0;
        }

        .el-checkbox__label {
          font-size: 12px;
          line-height: 36px;
          color: #999999;
          padding-left: 10px;
        }
      }
    }

    .check-box-title {
      margin-left: 80px;
      margin-bottom: 10px;
      margin-top: -10px;
    }

    .check-box {
      width: 55%;
      margin-left: 80px;
      margin-bottom: 30px;
      border: 1px solid #DCDFE6;
      padding: 10px;
      font-size: 12px;
      line-height: 36px;
      color: #999999;

      span {
        padding: 0 5px;
      }
    }

    .cell {
      .el-form-item {
        margin: 22px 0;
      }
    }

    .button {
      display: flex;
      justify-content: center;
      margin-top: 30px;
    }
  }

  .tabblebox {
    .el-form-item {
      margin: 30px 0 !important;
    }

    .el-input-number {
      width: 60px;

      .el-input__inner {
        padding: 0 5px !important;
      }
    }
  }
}
</style>
